package com.gxitsky.channel;

import lombok.Data;
import org.springframework.util.ClassUtils;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * @author gxing
 * @desc 请求配置
 * @date 2022/1/22
 */
@Data
public class RequestConfig {

    /**
     * 业务编码
     */
    private String bzCode;
    /**
     * 请求参数模板
     */
    private String requestTemplate;
    /**
     * 响应参数模板
     */
    private String responseTemplate;
    /**
     * 响应码模板
     */
    private String responseCodeTemplate;
    /**
     * 响应码Map
     */
    private Map<String, ResponseCode> responseCodeMap = new HashMap<>();
    /**
     * http 配置
     */
    private HttpConfig httpConfig;
    /**
     * 渠道配置
     */
    private ChannelConfig channelConfig;

    /**
     * @desc 初始化
     * @author gxing
     * @date 2022/1/24 10:39
     */
    protected void init() {
        InputStream in = ClassUtils.getDefaultClassLoader().getResourceAsStream(responseCodeTemplate);
        Map<String, List<String>> mappingCode = YamlHelper.parseYaml(in, Map.class);
        mappingCode.entrySet().forEach(e -> {
            ResponseCode responseCode = new ResponseCode();
            responseCode.setOuterCode(e.getKey());
            responseCode.setInnerCode(String.valueOf(e.getValue().get(0)));
            responseCode.setSuccess(e.getValue().get(1));
            if (e.getValue().size() > 2) {
                responseCode.setInnerMsg(e.getValue().get(2));
            }
            responseCodeMap.put(e.getKey(), responseCode);
        });

        Optional.ofNullable(httpConfig).ifPresent(h -> h.setRequestConfig(this));
    }
}
